<script setup>
import { reactive, ref, watch } from 'vue'
import ProductSelectDialog from '@/components/ProductSelectDialog.vue'
import { queryProductEcho } from '@/service/product.js'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { addNewSeckillProduct, updateSeckillProduct } from '@/service/seckill.js'
const showModal = ref(false)
const props = defineProps({
  type: {
    type: String,
    default: 'add', // add or update
  },
})
const emits = defineEmits(['update'])

const productSelectDialogRef = ref()
const seckillProductForm = reactive({
  seckillTime: null,
  seckillProduct: null,
  status: 0,
})

watch(showModal, (value) => {
  if (!value) {
    Object.assign(seckillProductForm, {
      seckillTime: null,
      seckillProduct: null,
      status: 0,
    })
  }
})
async function onReceiveProductInfo(event) {
  const productId = event[0].id
  const { data: productInfo } = await queryProductEcho(productId)
  seckillProductForm.seckillProduct = productInfo
}

function validForm() {
  // 验证时间
  if (!seckillProductForm.seckillTime) {
    ElMessage.error('请填写秒杀时间！')
    return false
  }
  // if (seckillProductForm.seckillTime[0].getTime() < new Date().getTime()) {
  //   ElMessage.error('秒杀时间不可以早于当前时间！')
  //   return false
  // }
  if (!seckillProductForm.seckillProduct) {
    ElMessage.error('请选择秒杀商品！')
    return false
  }
  // 校验秒杀价格
  const hasInvalidPrice = seckillProductForm.seckillProduct.productSpecifications.some(
    (productSpecification, index) => {
      const discountPrice = productSpecification.discountPrice
      const seckillPrice = productSpecification.seckillPrice

      if (discountPrice <= seckillPrice) {
        ElMessage.error(`请设置${index + 1}号规格的秒杀价格！`)
        return true // 触发 some 终止遍历
      }
      return false
    }
  )

  return !hasInvalidPrice
}

async function onTapSaveButton() {
  if (!validForm()) return
  const param = {}
  param.productId = seckillProductForm.seckillProduct.productId
  param.seckillStartTime = dayjs(seckillProductForm.seckillTime[0]).format('YYYY-MM-DD HH:mm:ss')
  param.seckillEndTime = dayjs(seckillProductForm.seckillTime[1]).format('YYYY-MM-DD HH:mm:ss')
  param.status = seckillProductForm.status
  param.seckillProductSpecificationDtoList = seckillProductForm.seckillProduct.productSpecifications.map((item) => {
    return {
      productSpecificationId: item.productSpecificationId,
      seckillPrice: item.seckillPrice,
      stock: item.stock,
    }
  })
  const res = await addNewSeckillProduct(param)
  if (res.code === 0) {
    ElMessage.error(res.message)
  } else {
    ElMessage.success('成功添加秒杀商品！')
    emits('update')
    showModal.value = false
  }
}
async function onTapUpdateButton() {
  if (!validForm()) return
  const param = {}
  param.productId = seckillProductForm.seckillProduct.productId
  param.seckillStartTime = dayjs(seckillProductForm.seckillTime[0]).format('YYYY-MM-DD HH:mm:ss')
  param.seckillEndTime = dayjs(seckillProductForm.seckillTime[1]).format('YYYY-MM-DD HH:mm:ss')
  param.status = seckillProductForm.status
  param.seckillProductSpecificationDtoList = seckillProductForm.seckillProduct.productSpecifications.map((item) => {
    return {
      productSpecificationId: item.productSpecificationId,
      seckillPrice: item.seckillPrice,
      stock: item.stock,
    }
  })
  const res = await updateSeckillProduct(param)
  if (res.code === 0) {
    ElMessage.error(res.message)
  } else {
    ElMessage.success('成功更新秒杀商品！')
    emits('update')
    showModal.value = false
  }
}
defineExpose({
  showModal,
  seckillProductForm,
})
</script>

<template>
  <el-dialog
    v-model="showModal"
    :title="props.type === 'add' ? '新增秒杀商品' : '编辑秒杀商品'"
    draggable
    width="1300px"
  >
    <el-form :model="seckillProductForm" label-position="right" label-width="120px">
      <el-form-item label="秒杀时段:" style="width: 500px">
        <el-date-picker
          v-model="seckillProductForm.seckillTime"
          end-placeholder="秒杀结束时间"
          range-separator="到"
          start-placeholder="秒杀开始时间"
          type="datetimerange"
        />
      </el-form-item>
      <el-form-item label="秒杀商品:">
        <template v-if="seckillProductForm.seckillProduct === null">
          <el-button type="primary" @click="productSelectDialogRef.showProductSelectDialog = true">
            新增秒杀商品
          </el-button>
        </template>
        <template v-else>
          <el-table
            :data="seckillProductForm.seckillProduct.productSpecifications"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            border
          >
            <el-table-column align="center" label="商品">
              <template #default="scope">
                <div class="product-info">
                  <img :src="scope.row.productSpecificationImage" alt="" />
                  <div class="product-name">
                    {{ seckillProductForm.seckillProduct.productName }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="商品规格">
              <template #default="scope">
                <span>{{ scope.row.productSpecificationName }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="商品价格">
              <template #default="scope">
                <span>￥{{ scope.row.discountPrice }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="秒杀价格">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.seckillPrice"
                  :controls="false"
                  :max="scope.row.discountPrice"
                  :precision="2"
                >
                  <template #prefix>
                    <span>￥</span>
                  </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column align="center" label="库存信息">
              <template #default="scope">
                <el-input-number v-model="scope.row.stock" :controls="false" :min="1" :precision="0"> </el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-form-item>
      <el-form-item label="秒杀状态:">
        <el-radio-group v-model="seckillProductForm.status">
          <el-radio :value="0">启用</el-radio>
          <el-radio :value="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-if="props.type === 'add'" type="primary" @click="onTapSaveButton"> 保存</el-button>
      <el-button v-else type="primary" @click="onTapUpdateButton">更新</el-button>
      <el-button @click="showModal = false">取消</el-button>
    </template>
  </el-dialog>
  <product-select-dialog
    ref="productSelectDialogRef"
    :product-type="0"
    type="radio"
    @on-tap-confirm-product="onReceiveProductInfo($event)"
  ></product-select-dialog>
</template>

<style lang="scss" scoped>
.product-info {
  display: flex;
  align-items: center;
  img {
    width: 60px;
    height: 60px;
  }
  .product-name {
    margin-left: 10px;
    font-size: 12px;
    text-align: left;
    line-height: 15px;
  }
}
</style>
